#include "organizedtextcontext.h"
#include "languagestrategy.h"
#include "engine/GameSystem.h"

OrganizedTextContext::OrganizedTextContext():
        _charsPerLine(10),
        _linesPerPage(3)
{
}

OrganizedTextContext::~OrganizedTextContext(){
}

void OrganizedTextContext::build(){
    XCHAR * str = _text->getText();
    int len = GameSystem::getStrLen(str);
    int charsInLine = 0;
    int linesInPage = 0;
    int currPage = 0;
    for(int i = 0; i < len; ++i){
        char c = str[i];
        // End of text
        if( i == len - 1 ){
            _lines.push_back(i);
            _paragraphs.push_back(i);
            _pages.push_back(i);
            return;
        }
        else if( c == '\n'){
            // End of line
            onEndOfLine(i, charsInLine, linesInPage, currPage);
            _paragraphs.push_back(i);
            continue;
        }
        else{
            int skipNum = _language->getCharsBeforeNewLine(str, i, charsInLine);
            if( skipNum + charsInLine >= _charsPerLine){
                onEndOfLine(i, charsInLine, linesInPage, currPage);
            }
            if( skipNum ){
                i += (skipNum - 1);
                charsInLine += (skipNum - 1);
                continue;
            }
        }
        if( ++charsInLine >= _charsPerLine ){
            onEndOfLine(i, charsInLine, linesInPage, currPage);
        }
    }
}

void OrganizedTextContext::onEndOfLine(int index, int& charsInLine, int& linesInPage, int& currPage){

    _lines.push_back(index);
    charsInLine = 0;
    // End of page
    if( ++linesInPage >= _linesPerPage ){
        _pages.push_back(index);
        linesInPage = 0;
        ++currPage;
    }
}
